import { Module } from "vuex";
import { ILoginState, ILoginMessage } from "./types";
import { IRootState } from "../types";
import {
  accountLoginRequest,
  accountLoginImgRequest
} from "@/service/login/login";
import { IAccount, IImg } from "@/service/login/type";
import router from "@/router";
import LocalCache from "@/utils/cache";
import { h } from "vue";
import { ElMessage } from "element-plus";
import { mapMenusToPermissions } from "@/utils/map-menus";
const loginModule: Module<ILoginMessage, IRootState> = {
  namespaced: true,
  // 此处就是state定义的类型
  state() {
    return {
      token: "",
      userinfo: {},
      imgUrl: ""
    };
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      // 简单粗暴的方法加any
      const loginResult = await accountLoginRequest(payload);
      const { data, total, errorMsg } = loginResult.data;
      if (total == 200) {
        commit("LOGINREQ", data);
        // 跳到首页
        // router.push("/main");
        router.push({
          name: "index"
        });
      } else {
        ElMessage({
          message: h("p", null, [
            h("span", null, "错误信息："),
            h("i", { style: "color: teal" }, errorMsg)
          ])
        });
      }
    },
    async accountImgAction({ commit }, payload: IImg) {
      const loginImg = await accountLoginImgRequest(payload);
      // let imgUrl = 'data:image/png;base64,' + btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      commit("SMSIMGREQ", loginImg);
    }
  },
  mutations: {
    LOGINREQ(state, data) {
      state.token = data;
      LocalCache.setCache("token", data);
    },
    SMSIMGREQ(state, data) {
      state.imgUrl =
        "data:image/png;base64," +
        btoa(
          new Uint8Array(data.data).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ""
          )
        );
    }
    // 获取用户按钮权限
    // 传入按钮权限的列表 （Menus）
    // const permissions = mapMenusToPermissions(Menus)
    // state.permission = Permissions
  },
  getters: {}
};

export default loginModule;
